//
//  SOAuthViewController.swift
//  SWeiboBoom
//
//  Created by Angus.丶 ShangYang on 16/8/10.
//  Copyright © 2016年 Angus_Shyang. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class SOAuthViewController: UIViewController {

    override func loadView() {
        view = webView
        //判断UIL  是否为空
        guard let url = NSURL(string:"https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirect_url)")else{
            return
        }
        
        //设置代理
        webView.delegate = self
        //实例化request
        let request = NSURLRequest(URL: url)
        //记载request
        webView.loadRequest(request)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }
    
    //MARK : - 监听方法
    //取消
    @objc private func cancelAction(){
        dismissViewControllerAnimated(false, completion: nil)
    }
    //自动填充
    @objc private func autofillAction(){
        print("自动填充")
        let jsString = "document.getElementById('userId').value='\(WBName)',document.getElementById('passwd').value='\(WBPassWd)'"
        //js注入
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    
    //MARK: - 设置视图
    private func setupUI(){
        
        view.backgroundColor = UIColor.whiteColor()
        setupNav()
    }
    
    //MARK: - 设置导航
    private func setupNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消",style: UIBarButtonItemStyle.Plain,target: self,action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充",style: UIBarButtonItemStyle.Plain,target: self,action: "autofillAction")
        navigationItem.title = "微博登录"
    }

    //MARK: - 懒加载控件
    private lazy var webView:UIWebView = UIWebView()

}

extension SOAuthViewController:UIWebViewDelegate{
    /*
            - 监听: webView 将要加载的request
                - 如果不实现  默认 返回true
                - 如果返回 false  停止加载request
     */
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //判断urlString 是否为nil  而且他的前缀是否为我们设置的回调页
        if let urlString = request.URL?.absoluteString where urlString.hasPrefix(WBRedirect_url){
            //query 请求参数
            //判断是否为nil
            if let query = request.URL?.query{
                
                //获取code(截取字符串)
                let code = query.substringFromIndex("code=".endIndex)
                print("我还是很喜欢你,就像雪白了地表,代我看你:\(code)")
                getUserAccount(code)
                
            }
            
        }
        return true
        
    }
    
    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        
    }
    //加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        
    }
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
    }
    
}

//MARK: - 请求数据
extension SOAuthViewController{
    //获取授权
    func getUserAccount(code:String){
        
        //请求urlString
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        //请求参数
        let params = [
        
            "client_id":WBAppKey,
            "client_secret":WBAppSecret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_url":WBRedirect_url
        ]
        //发送请求
        let manager = AFHTTPSessionManager()
        //序列化类型
        manager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        manager.POST(urlString, parameters: params, progress: nil, success: { (_, response) -> Void in
            print("请求成功:\(response)")
            //判断response 是否为 nil  而且是否可以转成一个字典
            //如果你使用 if - let 或者 gurad 判断可选值是否可以转成我们想要的类型  一般均使用as?
            guard let res = response as?[String:AnyObject]else{
                return
            }
            //通过字典创建一个模型
            let userAccount = SUserAccountModel(dict:res)
            print(userAccount)
            
            }) { (_, error) in
                print("请求失败:\(error)")
        }
    }

}

















